package cn.ava.user.service.impl;

import cn.ava.basic.constant.BaseConstants;
import cn.ava.basic.dto.EmailRegisterDto;
import cn.ava.basic.dto.SmsRegisterDto;
import cn.ava.basic.exception.BusinessException;
import cn.ava.basic.service.impl.BaseServiceImpl;
import cn.ava.basic.utils.CheckCodeUtil;
import cn.ava.basic.utils.MD5Utils;
import cn.ava.basic.utils.StrUtils;
import cn.ava.user.domain.Logininfo;
import cn.ava.user.domain.User;
import cn.ava.user.mapper.LogininfoMapper;
import cn.ava.user.mapper.UserMapper;
import cn.ava.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ava
 * @since 2022-07-06
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {


    @Autowired // redis连接
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired // user用户表map层
    private UserMapper userMapper;

    @Autowired // 登录信息表map层
    private LogininfoMapper logininfoMapper;


    /**
     * @Title: registerPhone
     * @Description: 用户注册
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/8 23:27
     * @param:
     * @return:
     */
    @Override
    public void registerUser(SmsRegisterDto smsRegisterDto) {
        String registerType = smsRegisterDto.getRegisterType();
        // 注册业务逻辑判断
        if (registerType.equals("phone")){
            String phone = smsRegisterDto.getPhone();
            String smsCodeValue = smsRegisterDto.getSmsCodeValue();
            // 正则表达式校验手机号格式是否正确
            if (!Pattern.matches(BaseConstants.VerifyShopSettlement.REGEX_MOBILE,phone)) {
                throw new BusinessException("请输入正确的手机号,请重新输入");
            }
            // 调用注册业务方法
            register(smsRegisterDto,phone,smsCodeValue);
        }else if(registerType.equals("email")) {
            String email = smsRegisterDto.getEmail();
            String emailCodeValue = smsRegisterDto.getEmailCodeValue();
            // 正则表达式校验手机号格式是否正确
            if(!Pattern.matches(BaseConstants.VerifyShopSettlement.REGEX_EMAIL,email)){
                throw new BusinessException("请输入正确的邮箱,请重新输入");
            }
            // 调用注册业务方法
            register(smsRegisterDto,email,emailCodeValue);
        }else {
            throw new BusinessException("参数异常！请重试");
        }
    }

    @Override
    public User getByLogininfoId(Long id) {
        return userMapper.getByLogininfoId(id);
    }

    /**
     * @Title: register
     * @Description: 用户注册抽取方法
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/12 11:09
     * @param:
     * @return:
     */
    @Transactional
    public void register(SmsRegisterDto smsRegisterDto,String username,String code){
        String password = smsRegisterDto.getPassword();
        String confirmPassword = smsRegisterDto.getConfirmPassword();
        // 调用非空校验工具类
        CheckCodeUtil.checkEmpty(username,password,confirmPassword,code);
        // 调用短信验证码校验工具类
        CheckCodeUtil.checkSmsCode(redisTemplate
                ,BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY
                ,username
                ,code);
        // 判断密码是否一致
        if (!password.equals(confirmPassword)) {
            throw new BusinessException("两次密码不一致！请重新输入");
        }
        // 判断用户是否已注册，如果已注册提示用户
        User user = null;
        if (smsRegisterDto.getRegisterType().equals("phone")){
            user = userMapper.getByPhone(username);
        }else if (smsRegisterDto.getRegisterType().equals("email")){
            user = userMapper.getByEmail(username);
        }
        if (user != null){
            throw new BusinessException("用户已注册，请直接登录，如果忘记密码，请点击忘记密码！");
        }
        // 已经不为空，直接使用user对象
        // 将smsCodeDto数据拷贝到user中
        user = smsCodeDto2User(smsRegisterDto);
        // 将user数据拷贝到Logininfo中
        userMapper.add(user);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.update(user);

    }

    /**
     * @Title: smsCodeDto2User
     * @Description: 初始化user
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/11 16:18
     * @param:
     * @return:
     */
    private User smsCodeDto2User(SmsRegisterDto smsRegisterDto) {
        // 获取对象
        User user = new User();
        String password = smsRegisterDto.getPassword();
        if (smsRegisterDto.getRegisterType().equals("phone")){
            // 获取参数
            String phone = smsRegisterDto.getPhone();
            // 设置属性
            user.setUsername(phone);
            user.setPhone(phone);
        }else if(smsRegisterDto.getRegisterType().equals("email")) {
            // 获取参数
            String email = smsRegisterDto.getEmail();
            // 设置属性
            user.setUsername(email);
            user.setEmail(email);
        }
        // 获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 获取MD5进行加盐加密
        String md5Password = MD5Utils.encrypByMd5(salt + password);
        user.setSalt(salt);
        user.setPassword(md5Password);
        return user;
    }

    /**
     * @Title: user2Logininfo
     * @Description: 注册成功保存信息到登录表
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/11 16:18
     * @param:
     * @return:
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        // 拷贝user对象
        BeanUtils.copyProperties(user,logininfo);
        // 设置用户类型
        logininfo.setType(1);
        return logininfo;
    }






}
